package com.mes.web.controller.biz;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

import com.mes.biz.domain.BizProductCategory;
import com.mes.biz.domain.vo.ImportProduct;
import com.mes.biz.domain.vo.ProductVo;
import com.mes.biz.service.BizProductCategoryService;
import com.mes.common.annotation.Log;
import com.mes.common.constant.Constants;
import com.mes.common.core.domain.AjaxResult;
import com.mes.common.core.domain.R;
import com.github.pagehelper.PageInfo;
import com.mes.common.core.domain.TreeNode;
import com.mes.common.core.domain.entity.SysUser;
import com.mes.common.core.domain.model.LoginUser;
import com.mes.common.core.page.PageDomain;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mes.common.enums.BusinessType;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.poi.ExcelUtil;
import com.mes.framework.cache.DictUtils;
import javax.validation.constraints.*;

import com.mes.system.domain.SysConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.mes.common.core.controller.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import com.mes.biz.domain.BizProduct;
import com.mes.biz.service.BizProductService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品Controller
 * @author hwg
 * @email hwg
 * @date 2023-04-02
 */
@RestController
@RequestMapping("/biz/bizProduct")
public class BizProductController extends BaseController {

    @Autowired
    private BizProductService bizProductService;
    @Resource
    private BizProductCategoryService bizProductCategoryService;

    /**
     * 查询产品列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:list')")
    @GetMapping("/list")
    public R<PageInfo> list(BizProduct bizProduct, HttpServletRequest request, HttpServletResponse response) {
        bizProduct.setPage(new PageDomain(request, response));
        List<BizProductCategory> bizProductCategoryList = bizProductCategoryService.findList(null);
        if(bizProduct.getCategoryId()!=null) {
            String categoryIds = bizProductCategoryService.getSelfAndSubIds(bizProduct.getCategoryId(),bizProductCategoryList,new StringBuffer());
            bizProduct.setCategoryId(categoryIds);
        }
        return R.data(bizProductService.findPage(bizProduct));
    }


    /**
     * 获取产品详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:query')")
    @GetMapping(value = "/{id}")
    public R<BizProduct> detail(@PathVariable("id") String id) {
        return R.data(bizProductService.get(id));
    }

    /**
     * 新增产品
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:add')")
    @Log(title = "产品", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated  BizProduct bizProduct) {
        bizProduct.setTenantId(SecurityUtils.getTenantId());
        return R.status(bizProductService.createProduct(bizProduct));
    }

    /**
     * 修改产品
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:edit')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated BizProduct bizProduct) {
        return R.status(bizProductService.save(bizProduct));
    }

    /**
     * 删除产品
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:remove')")
    @Log(title = "产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(bizProductService.deleteBizProductByIds(ids));
    }


    /**
     * 导出产品列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProduct:export')")
    @Log(title = "产品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(BizProduct bizProduct) {
        List<BizProduct> list = bizProductService.findList(bizProduct);
        ExcelUtil<BizProduct> util = new ExcelUtil<BizProduct>(BizProduct.class);
        return util.exportExcel(list, "产品数据");
    }

    /**
     * 根据字典类型查询字典数据信息等其他自定义信息
     */
    @GetMapping(value = "/getInitData/{dictTypes}")
    public R getInitData(@PathVariable String dictTypes) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.putAll(DictUtils.getMultiDictList(dictTypes));
        return R.data(dataMap);
    }

    /**
     * 查询产品树结构
     * @param level
     * @return
     */
    @PreAuthorize("@ss.hasPermi('biz:bizProductCategory:list')")
    @GetMapping("/listTree/{level}/{id}")
    public R listTree(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<TreeNode> bizProductList = bizProductService.buildTree(level, id);
        return R.data(bizProductList);
    }

    @PreAuthorize("@ss.hasPermi('biz:bizProduct:edit')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdate")
    public R batchUpdate(@RequestBody @Validated ProductVo productVo) {
        return R.status(bizProductService.batchUpdate(productVo));
    }

    @Log(title = "期初明细导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,String warehouseId) throws Exception {
        ExcelUtil<ImportProduct> util = new ExcelUtil<ImportProduct>(ImportProduct.class);
        List<ImportProduct> bizProductList = util.importExcel(file.getInputStream());
        return bizProductService.importData(bizProductList,warehouseId);
    }

    @GetMapping("/importTemplate")
    public R importTemplate() {
        ExcelUtil<ImportProduct> util = new ExcelUtil<ImportProduct>(ImportProduct.class);
        return util.importTemplateExcel("明细导入");
    }

    @PreAuthorize("@ss.hasPermi('biz:bizProduct:edit')")
    @Log(title = "校验产品", businessType = BusinessType.CHECK)
    @GetMapping("/checkDataUnique")
    public R checkDataUnique(BizProduct bizProduct) {
        Map<String, String> checkMap = new HashMap<String, String>(1);
        try {
            bizProductService.checkDataUnique(bizProduct);
            checkMap.put("code", "1");
        } catch (Exception e) {
            checkMap.put("code", "2");
        }
        return R.data(checkMap);
    }

    @GetMapping("/appletList")
    public R<PageInfo> appletList(BizProduct bizProduct, HttpServletRequest request, HttpServletResponse response) {
        bizProduct.setPage(new PageDomain(request, response));
        List<BizProductCategory> bizProductCategoryList = bizProductCategoryService.findList(null);
        if(bizProduct.getCategoryId()!=null) {
            String categoryIds = bizProductCategoryService.getSelfAndSubIds(bizProduct.getCategoryId(),bizProductCategoryList,new StringBuffer());
            bizProduct.setCategoryId(categoryIds);
        }
        return R.data(bizProductService.findPage(bizProduct));
    }
}
